# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from waveapi import events
from waveapi import robot
from waveapi import appengine_robot_runner
import logging
import wordnik

FILTER_KEY = "wordnik-annotate"

### Get your own Wordnik API key from http://api.wordnik.com/signup/
### And then drop it into a file called 'wordnik_api_key'.  Make sure this
### file stays out of version control.  :-).

WORDNIK_API_KEY = open('wordnik_api_key', 'r').readline().strip()
w = wordnik.Wordnik(WORDNIK_API_KEY)


def GetDefinition(word):
  """Fetch a single-word definition from Wordnik"""
  try:
    definition = w.definitions(word)[0]['text']
    return '"' + definition + '"'
  except:
    return '(definition not found; make sure only one word is highlighted)'


def OnAnnotationChanged(event, wavelet):
  """Insert wordnik definition child blip after annotated text."""
  blip = event.blip
  text = blip.text

  todo = []
  for ann in blip.annotations:
    if ann.name == FILTER_KEY:
      todo.append((ann.start, ann.end, ann.value))

  for start, end, value in todo:
    payload = text[start:end]
    blip.range(start, end).clear_annotation(FILTER_KEY)
    definition = GetDefinition(payload)
    if definition:
       inlineBlip = blip.insert_inline_blip(end + 1)
       inlineBlip.append(definition)


if __name__ == '__main__':
  myRobot = robot.Robot('Wordnik Bot', 
      image_url='http://wordnikbot.appspot.com/assets/icon.png',
      profile_url='http://wordnikbot.appspot.com/')
  myRobot.register_handler(events.AnnotatedTextChanged,
                           OnAnnotationChanged, filter=FILTER_KEY)
  myRobot.register_handler(events.WaveletSelfAdded,
                           OnAnnotationChanged)
  appengine_robot_runner.run(myRobot)

  
